<template>
    <el-dialog :title="title" :visible.sync="visible" width="560px" append-to-body :close-on-click-modal="false">
        <BaseForm2
            ref="form"
            v-loading="loading"
            label-position="right"
            label-width="86px"
            :fields="fields"
            :text-model="false"
            :data="form"
            size="medium"
            @updateValue="updateEvent"
        ></BaseForm2>
        <div slot="footer" class="dialog-footer">
            <BaseButton :loading="submitLoading" @click="submitForm">保 存</BaseButton>
            <BaseButton type="recond" @click="cancel">取 消</BaseButton>
        </div>
    </el-dialog>
</template>

<script>
import BaseForm2 from '@/components/BaseForm2'
import { DirectionOptions } from '@/config/constants'
import { LineHighwayModel, MaintenanceRecordModel } from '@/models'
import { DrivewayTypeOptions, MaintenanceEngineeringOptions, MaintenanceTypeOptions } from '@/views/auxiliary-decision/constants'
export default {
    name: 'AddOrUpdate',
    components: {
        BaseForm2
    },
    data() {
        return {
            lineHighwayModel: new LineHighwayModel(),
            model: new MaintenanceRecordModel(),
            title: '新增养护维修记录',
            visible: false,
            submitLoading: false,
            loading: false,
            form: {},
            id: '',
            fields: [
                {
                    label: '',
                    children: [
                        {
                            options: [],
                            key: 'highwayCode',
                            valueKey: 'label',
                            label: '公路编码',
                            type: 'normal-select',
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            key: 'highwayName',
                            type: 'input',
                            label: '公路名称',
                            span: 24,
                            disableDefault: true,
                            rules: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }]
                        },
                        {
                            key: 'orgName',
                            label: '管养单位',
                            type: 'input',
                            span: 24,
                            disableDefault: true,
                            rules: [{ required: true, message: '必填项', trigger: ['blur', 'change'] }]
                        },
                        {
                            options: DirectionOptions,
                            key: 'direction',
                            valueKey: 'label',
                            label: '方向',
                            type: 'normal-select',
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: DrivewayTypeOptions,
                            key: 'lane',
                            valueKey: 'label',
                            label: '车道',
                            type: 'normal-select',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }],
                            span: 24
                        },
                        {
                            key: 'startStakeNo',
                            label: '起点桩号',
                            span: 24,
                            type: 'stake'
                        },
                        {
                            key: 'endStakeNo',
                            label: '终点桩号',
                            span: 24,
                            type: 'stake'
                        },
                        {
                            key: 'maintYear',
                            type: 'date-input',
                            format: 'yyyy',
                            'value-format': 'yyyy',
                            defaultType: 'year',
                            label: '养护年度',
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: MaintenanceEngineeringOptions,
                            key: 'maintProject',
                            valueKey: 'label',
                            label: '养护工程',
                            type: 'normal-select',
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: MaintenanceTypeOptions,
                            key: 'maintCategory',
                            valueKey: 'label',
                            label: '养护类别',
                            type: 'normal-select',
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            key: 'maintMeasure',
                            type: 'textarea',
                            label: '养护措施',
                            maxlength: '300',
                            'show-word-limit': true,
                            required: true,
                            span: 24,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        }
                    ]
                }
            ]
        }
    },
    created() {
        this.getHighwayList()
    },
    methods: {
        updateEvent(data) {
            // 根据选择的公路编号回填公路名称和养护机构
            if (data.highwayCode) {
                const { highwayName, orgName } = this.fields[0].children[0].options.find((item) => item.label === data.highwayCode) || {}
                this.$refs.form.updateFormData({ highwayName, orgName })
            }
        },
        getHighwayList() {
            this.lineHighwayModel.getList({}, { pageNo: 1, pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        label: item.code,
                        value: item.id,
                        highwayName: item.name,
                        orgName: item.managementName
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[0], 'options', list)
            })
        },
        // 取消按钮
        cancel() {
            this.visible = false
            this.reset()
        },
        async open(options = {}) {
            const { type, id = null } = options
            this.id = id
            this.visible = true
            this.reset()
            if (type === 'add') {
                this.title = '新增养护维修记录'
            } else {
                this.title = '修改养护维修记录'
                const res = await this.getDetail()
                res.startStakeNo = res.startStakeNo.replace('K', '').split('+')
                res.endStakeNo = res.endStakeNo.replace('K', '').split('+')
                this.form = res
            }
        },
        // 表单重置
        reset() {
            this.$nextTick(() => {
                this.$refs['form'].resetFields()
            })
        },
        getDetail() {
            this.loading = true
            return this.model.detail({ id: this.id }).finally(() => {
                this.loading = false
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid, res) => {
                if (valid) {
                    console.log(res)
                    this.submitLoading = true
                    const startStakeNo = `K${res.startStakeNo[0]}+${res.startStakeNo[1]}`
                    const endStakeNo = `K${res.endStakeNo[0]}+${res.endStakeNo[1]}`
                    const data = {
                        ...res,
                        startStakeNo,
                        endStakeNo
                    }
                    this.id && (data.id = this.id)
                    this.model
                        .saveOrUpdate(data)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.visible = false
                                    this.$emit('success')
                                }
                            })
                        })
                        .finally(() => {
                            setTimeout(() => {
                                this.submitLoading = false
                            }, 1000)
                        })
                } else {
                    this.$message.error('校验失败！')
                }
            })
        }
    }
}
</script>
